﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admintool.ExtensionMethods;
using Admintool.Infrastructure;
using EM.LVB.OMS.IPTool;

namespace Admintool
{
    partial class Program
    {
        [Command("export reg data with ip and mobile origin")]
        public static void GenRegDataResult(
            [Required(Description = "source file path")]string source,
            [Optional("true", new string[] { "s" }, Description = "indicates source file has headers or not ")] string hasHeaders)
        {
            //source field:uid	displayname	sid	origin	ip	mobphone	registertime	emuid	deviceinfo
            int index = 0;
            bool fstRowIsHeader = ConsoleHelper.GetValue<bool>(hasHeaders, false);
            string[] headers = "uid	displayname	sid	origin	ip	mobphone	registertime	emuid	deviceinfo".Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
            string[] appendCols = "m-region	m-sp	ip-regin	ip-sp".Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
            DataTable result = GenDataSchema("em_live_userinfo", headers, appendCols);
            IEnumerableExtension.ReadFromFile(source).ForEach((string line) => {
                if (!fstRowIsHeader || index++ != 0)
                {
                    GenResultRow(result, line);
                }
            });
            result.AcceptChanges();
            result.WriteXml(@"d:\data_xml.xml");
            ConsoleHelper.ShowMessage("====YOUR command has completed!", ConsoleColor.Green);
        }


        static void GenResultRow(DataTable result, string line)
        {
            string[] parts = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
            string ip = parts.Value<string>(4);
            string mobile = parts.Value<string>(5);
            DataRow dr = result.NewRow();
            dr["uid"] = string.Format("'{0}", parts.Value<string>(0));      // parts[0];
            dr["displayname"] = parts.Value<string>(1);
            dr["sid"] = string.Format("'{0}", parts.Value<string>(2));
            dr["origin"] = parts.Value<string>(3);
            dr["ip"] = ip; //parts.Value<string>(4);
            dr["mobphone"] = string.Format("'{0}", mobile);//parts.Value<string>(5);
            dr["registertime"] = parts.Value<string>(6);
            dr["emuid"] = string.Format("'{0}", parts.Value<string>(7));
            dr["deviceinfo"] = parts.Value<string>(8);

            if (mobile.Length >= 7)
            {
                Tuple<string, string, string> mobileentry = GetMobileIP(mobile.Substring(0, 7));
                dr["m-region"] = mobileentry != null ? mobileentry.Item1 : string.Empty;
                dr["m-sp"] = mobileentry != null ? mobileentry.Item3 : string.Empty;
            }
            IPEntity ipentry = IPCore.GetIPEntity(ip);
            dr["ip-regin"] = ipentry.Province;
            dr["ip-sp"] = ipentry.NetworkOperator;
            result.Rows.Add(dr);
        }

        static DataTable GenDataSchema(string tableName, string[] headers, string[] appendCols)
        {
            DataTable table = new DataTable(tableName);
            foreach (string col in headers.Union(appendCols))
            {
                if (!string.IsNullOrEmpty(col))
                {
                    table.Columns.Add(col, typeof(String));
                }
            }
            return table;
        }

        static Dictionary<string, Tuple<string, string, string>> s_mobiles = new Dictionary<string, Tuple<string, string, string>>();
        
        static Tuple<string, string, string> GetMobileIP(string mobile)
        {
            if (s_mobiles.Count <= 0)
            {
                string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["MobileDataPath"]);
                IEnumerableExtension.ReadFromFile(file).ForEach((string line) => {
                    string[] parts = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length == 4)
                    {
                        var item = Tuple.Create<string, string, string>(parts[1], parts[2], parts[3]);
                        s_mobiles.Add(parts[0], item);
                    }
                });
            }
            return s_mobiles.ContainsKey(mobile) ? s_mobiles[mobile] : null;
        }

    }
}
